package user

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/user"
	ServiceAdmin "gq_volunteer_platform/service/admin"
	"gq_volunteer_platform/service/message_queue"

	"github.com/gin-gonic/gin"
	"github.com/lluck42/tools"
)

func List(c *gin.Context) {

	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		Keyword        string `binding:"max=255"`
		CheckStatus    string `binding:"oneof='' 待审核 已审核 已驳回"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	// 查询
	var count int64
	var list []struct {
		ID             uint `gorm:"primarykey;->"`
		OrganizationId uint
		Name           string
		RealName       string
		ProfilePhoto   string
		MobileNumber   string
		LastIp         string
		LastLoginTime  string
		ServeHour      int
		Point          int
		CheckStatus    string
		ChangeStatus   string
		CheckNote      string
		CreatedAt      string
	}

	var tx = bean.MysqlDb.Model(&user.User{})

	if req.Keyword != "" {
		tx = tx.Where("`name` like ?", "%"+req.Keyword+"%").Or("`real_name` like ?", "%"+req.Keyword+"%").Or("`mobile_number` like ?", "%"+req.Keyword+"%")
	}

	tx = tx.Where("`mobile_number` != ''")
	// {
	// 	c.PureJSON(200, gin.H{
	// 		"count": 0,
	// 		"list":  list,
	// 	})
	// 	return
	// }

	if req.CheckStatus != "" {
		tx = tx.Where("`check_status`=?", req.CheckStatus)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func MyList(c *gin.Context) {

	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		Name           string `binding:"max=255"`
		CheckStatus    string `binding:"oneof='' 待审核 已审核 已驳回"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	// 查询
	var count int64
	var list []struct {
		ID             uint `gorm:"primarykey;->"`
		OrganizationId uint
		Name           string
		RealName       string
		ProfilePhoto   string
		MobileNumber   string
		LastIp         string
		LastLoginTime  string
		ServeHour      int
		Point          int
		CheckStatus    string
		ChangeStatus   string
		CheckNote      string
		CreatedAt      string
	}

	var tx = bean.MysqlDb.Model(&user.User{})

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, req.OrganizationId)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	tx = tx.Where("`organization_id` in ?", organization_my_ids)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%").Or("`real_name` like ?", "%"+req.Name+"%").Or("`mobile_number` like ?", "%"+req.Name+"%")
	}

	if req.CheckStatus != "" {
		tx = tx.Where("`check_status`=?", req.CheckStatus)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func Detail(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one user.User

	if err := bean.MysqlDb.Model(&user.User{}).Where("`id`=?", req.ID).Take(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, fmt.Sprintf("数据库错误id:%d", req.ID))
		return
	}

	// 权限验证
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	c.PureJSON(200, one)
}

func Check(c *gin.Context) {

	var req struct {
		ID          uint   `binding:"max=10000000"`
		CheckStatus string `binding:"oneof=已驳回 已审核"`
		CheckNote   string `binding:"max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one user.User

	if err := bean.MysqlDb.Model(&user.User{}).Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("用户不存在id:%d", req.ID))
		return
	}

	// 验证是否有修改权限 只能审核自己组织的成员
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var two user.User
	two.ID = one.ID
	two.CheckStatus = req.CheckStatus
	two.CheckNote = req.CheckNote

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
	// 发送通知 jldtx
	var user_list user.User
	if err := bean.MysqlDb.Where("`id`=?", two.ID).First(&user_list).Error; err != nil {
		bean.Log.Error(err)
		return
	}
	var Openid = user_list.Openid
	var page = "pages/user/main/index"
	var applyProject = "志愿者申请"
	var applyTime = user_list.CreatedAt
	var applyResult = ""
	if req.CheckStatus == "已审核" {
		applyResult = "您的申请已通过"
	} else if req.CheckStatus == "已驳回" {
		applyResult = "您的申请已驳回"
	}
	if err := message_queue.MessageQueueAddT1(Openid, page, applyProject, applyTime, applyResult); err != nil {
		// 错误记录
		bean.Log.Error(err)
	}

}

func ExitOrganization(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one user.User

	if err := bean.MysqlDb.Model(&user.User{}).Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("用户不存在id:%d", req.ID))
		return
	}

	// 验证是否有修改权限 只能审核自己组织的成员
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var two user.User
	two.ID = one.ID
	two.OrganizationId = 0
	two.CheckStatus = "待申请"
	two.CheckNote = "您已被管理员移出志愿者队伍"

	if err := bean.MysqlDb.Select("organization_id", "check_status", "check_note").Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
}

func ReducePoint(c *gin.Context) {

	var req struct {
		ID    uint   `binding:"max=10000000"`
		Point int    `binding:"min=1,max=10000000"`
		Note  string `binding:"max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one user.User

	if err := bean.MysqlDb.Model(&user.User{}).Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("用户不存在id:%d", req.ID))
		return
	}

	if one.Point < req.Point {
		bean.Log.Warning(fmt.Sprintf("用户积分不足：%d < %d", one.Point, req.Point))
		c.String(400, fmt.Sprintf("用户积分不足：%d < %d", one.Point, req.Point))
		return
	}

	// 验证是否有修改权限 只能审核自己组织的成员
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var tx = bean.MysqlDb.Begin()

	if err := user.ReducePoint(tx, one.ID, req.Point, "积分核销："+req.Note); err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 提交执行
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

func PointRecordList(c *gin.Context) {

	var req struct {
		ID    uint `binding:"max=10000000"`
		Page  int  `binding:"required,gte=1,max=10000000"`
		Limit int  `binding:"required,gte=1,max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var count int64
	var list []user.UserPointRecord

	var tx = bean.MysqlDb.Model(&user.UserPointRecord{}).Where("`user_id`=?", req.ID)

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})

}
